/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"fmt"
	"os"

	"github.com/opentracing/opentracing-go"
	"github.com/spf13/cobra"
	"github.com/uber/jaeger-client-go"
	"go.uber.org/zap/zapcore"

	log "atomgit.com/atomgit_dev/alog/alogcore"
	"atomgit.com/atomgit_dev/git-hooks/pkg/config"
)

// Version is the version of git-hooks, which is set by makefile
var Version = "unknown"

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "git-hooks",
	Short: "git-hooks implements pre-receive、post-receive and other useful hooks of git",
	Long: `git-hooks is the single point of entry for git and satellite to call git hooks. 
Actually git-hooks only serve as a grpc client, real function of git hooks is implemented in
satellite

current version: ` + Version,
	Version: Version,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(config.LoadConfig, initALog, initTracing)
}

func initALog() {
	c := config.Cfg.Alog
	var level zapcore.Level
	switch c.Level {
	case "debug":
		level = zapcore.DebugLevel
	case "info":
		level = zapcore.InfoLevel
	case "warn":
		level = zapcore.WarnLevel
	case "error":
		level = zapcore.ErrorLevel
	case "panic":
		level = zapcore.ErrorLevel
	case "fatal":
		level = zapcore.FatalLevel
	default:
		level = zapcore.ErrorLevel
	}
	log.InitLogger(c.FilePath, level, c.MaxSize, c.MaxBackup, c.MaxAge, c.Compress, false, c.ServiceName)
}

func initTracing() {
	tracer, _ := jaeger.NewTracer("hooks", jaeger.NewConstSampler(true), jaeger.NewNullReporter())
	opentracing.SetGlobalTracer(tracer)
}
